package uit.edu.vn.Activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;

import uit.edu.vn.Contact.MyContact;
import uit.edu.vn.Contact.imContact;
import uit.edu.vn.Utility.AESControl;
import uit.edu.vn.Utility.CheckInternet;
import uit.edu.vn.Utility.Contact;
import uit.edu.vn.Utility.MyActivity;
import uit.edu.vn.Utility.httpUploader;
import uit.edu.vn.Utility.xStreamXML;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;

import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Contacts;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class ContactBackupActivity extends MyActivity implements View.OnCreateContextMenuListener{

        //private String urlString = "http://10.0.2.2:8080/ServerWeb/UploadServlet.jsp";
        private int numberOfItemSelected = 0;
        private int     item_position_long_clicked;
        private ArrayList<imContact> imContactList= new ArrayList<imContact>();
        private ListView listview;
        private ArrayAdapter<imContact> arrayAdapter;
        private Contact contact;
      
        private static ProgressDialog progessDialog;
        private EditText edt_name;        
        private AlertDialog.Builder nameDialog;   
        private Context context;
        private TextView titleHeader;
        private Resources res;
        private String path = Environment.getExternalStorageDirectory()+"/BackupManager/Contact";
        private int contactFileType = 1;
        private AESControl aes;
        private String urlString = null;
        private String userid = null;
        private String username = "";
        private String password = "";
        private static final String STRING_NAME_USERSETTING = "USER REFERENCES";
        private SharedPreferences ShareRef = null;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        	
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            
            username = getSetting("username");
            password = getSetting("password");
            userid   = getSetting("userid");
            urlString = "http://"+ getSetting("address")+"/ServerWeb/UploadServlet.jsp";
            
            setContentView(R.layout.backup_file);
           
            //kiem tra neu username va password rong thi ket thuc activity hien tai va goi activity dang nhap
            if(username.equals("") && password .equals("")){
                Intent intent = new Intent(ContactBackupActivity.this, LoginActivity.class);
                startActivity(intent);
                this.finish();                
            }
            
            System.out.println("ContactBackupActivity");
            System.out.println("username: "+ username);
            System.out.println("password: "+ password);
            System.out.println("userid:   "+ userid);
            System.out.println("address:   "+ urlString);
			File dir = new File(path);
			dir.mkdirs();
            listview = (ListView)findViewById(R.id.listFileBackup);  
            titleHeader=(TextView)findViewById(R.id.txt_titleFile);
    		titleHeader.setText(R.string.title_BackupHeaderContact);
    		progessDialog= new ProgressDialog(this);
    		progessDialog.setMessage(getResources().getString(R.string.dialog_message_progress));
    		progessDialog.setCancelable(false);
    		progessDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            context = getBaseContext();
            nameDialog = new AlertDialog.Builder(this);
            edt_name = new EditText(this);
            nameDialog.setView(edt_name);
            res=getResources();
            new BackGroundTask().execute();
            listview.setOnItemClickListener(new OnItemClickListener() {
                @SuppressWarnings("deprecation")
                //bat su kien click chon 1 doi tuong cua list
        		@Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {                       
                    // TODO Auto-generated method stub
                    try {
                    	 Intent intent = new Intent(Intent.ACTION_VIEW);
                      //  showToast("click chon 1 contact");
                        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(imContactList.get(arg2).getId()));
                        Uri uri2 = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, null);
                        System.out.println("uri2in contact: "+uri2.toString().trim());
                        System.out.println("uri in contact: "+uri.toString().trim());
                        System.out.println( imContactList.get(arg2).getId());
                        System.out.println( imContactList.get(arg2).getDisplayName());
                        System.out.println( imContactList.get(arg2).getAddresses());
                        intent.setData(uri);
                        startActivity(intent);
                    } catch (Exception e) {
                    	new AlertDialog.Builder(ContactBackupActivity.this).setMessage(e.getMessage()).show();
                    }
                }
            });
        }
        
    	public String getSetting(String key) {
            ShareRef = getSharedPreferences(STRING_NAME_USERSETTING, Context.MODE_WORLD_WRITEABLE);
            return ShareRef.getString(key, "");
    	}  
    	
        private class BackGroundTask extends AsyncTask<Void, Void, Void>
        {
        	@Override
        	protected void onPreExecute() 
        	{
        		// TODO Auto-generated method stub
        		super.onPreExecute();
        		progessDialog.show();
        	}
        	@Override
        	protected Void doInBackground(Void... params) {
        		// TODO Auto-generated method stub
        		// imContactList.clear();
        		 addToListView(); 
        		 if(imContactList == null){
        			 showToast("Danh bạ trống");
        		 }
        		
        		 return null;
        	}
        	@Override
        	protected void onPostExecute(Void result) {
        		// TODO Auto-generated method stub
        		progessDialog.dismiss();
        		arrayAdapter = new ArrayAdapter<imContact>(context, R.layout.row_contact, imContactList) {
                      @Override
                      public View getView(int position, View v, ViewGroup parent) {
                          if (v == null) {
                              LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                              v = vi.inflate(R.layout.row_contact, null);
                          }
                          imContact imcontact = imContactList.get(position);
                          if (imcontact != null) {
                              TextView txtTopLeft = (TextView) v.findViewById(R.id.tvTopLeftInfo);
                              TextView txtTopRight = (TextView) v.findViewById(R.id.tvTopRightInfo);
                              TextView txtBottomRight = (TextView) v.findViewById(R.id.tvBottomRightInfo);
                              TextView txtBottomLeft = (TextView) v.findViewById(R.id.tvBottomLeftInfo);


                              ImageView iv = (ImageView) v.findViewById(R.id.ImageContact);                              
//                              iv.setImageBitmap(R.drawable.ic_contact_picture);
//                              iv.setImageDrawable(res.getDrawable(R.drawable.ic_launcher));
//                              iv.set
//                              res.getDrawable(R.drawable.ic_contact_picture);
//                              iv.setImageBitmap(imcontact.getBitmap());
                              

//                              ImageView iv = (ImageView) v.findViewById(R.id.ImageContact);
                           //   Bitmap bmp=imcontact.getBitmap();           
                              //iv.setImageBitmap();

                              CheckBox chkSelect = (CheckBox) v.findViewById(R.id.chkSelectContact);
                              chkSelect.setChecked(imcontact.isChecked());
                              
                              HashMap<String, String> info = contact.getContactShow(imcontact);
                              txtTopLeft.setText(imcontact.getDisplayName());
                              txtTopLeft.setText(imcontact.getFirstName(info.get("DisplayName")));
                              txtTopRight.setText(imcontact.getLastName(info.get("DisplayName")));
                              txtBottomRight.setText(info.get("BottomRightInfo"));
                              txtBottomLeft.setText(info.get("BottomLeftInfo"));
                              
//                              System.out.println("id of -------" +imcontact.getDisplayName().toString()+"------is------  "+imcontact.getId().toString());
                          }
                          return v;
                      }
                  };
        		listview.setAdapter(arrayAdapter);  
        		super.onPostExecute(result);
        	}
        }
        private void addToListView(){
            try{
            //lay du lieu cua danh ba dua vao doi tuong danh sach danh ba
            contact = new Contact(getContentResolver(), getContentResolver().query( ContactsContract.Contacts.CONTENT_URI, null, null, null, "display_name ASC"));
            imContactList = contact.getAllBaseContact(); 
            //dua du lieu hien thi tren list view
            }catch(Exception ex){
            	System.out.println("list contact error: "+ex.toString());
            }
        }      
        private void countItemChecked() {
            numberOfItemSelected = 0;
            for (int i = 0; i < imContactList.size(); i++) {
                if (imContactList.get(i).isChecked()) {
                    numberOfItemSelected++;
                }
            }
        }
        
        //su kien click check box o moi dong
        public void contactCheckButtonClick(View v) {
                CheckBox chk = (CheckBox) v;
                int pos = listview.getPositionForView(v);
                System.out.println("pos delete: "+pos);
                MyContact myContact = arrayAdapter.getItem(pos);
                myContact.setChecked(chk.isChecked());
                imContactList.get(pos).setChecked(chk.isChecked());
                numberOfItemSelected += chk.isChecked() ? 1 : -1;
                System.out.println("numberOfItemSelected : "+numberOfItemSelected);
                System.out.println("id of contact : "+imContactList.get(pos).getId().toString());
        }        
        
        //Tao menu context de thao tac tren tung danh ba(sua, xoa...)
        public void onCreateContextMenu(ContextMenu contextMenu, View v, ContextMenuInfo contextMenuInfo) {
                AdapterView.AdapterContextMenuInfo info;
                try {
                        info = (AdapterView.AdapterContextMenuInfo) contextMenuInfo;
                } catch (ClassCastException e) {
                        return;
                }
                contextMenu.setHeaderTitle(imContactList.get(item_position_long_clicked = info.position).getDisplayName());
                new MenuInflater(getApplication()).inflate(R.menu.backup_contact_context_menu, contextMenu);
        }        
        //xu ly su kien click chon context menu item
        @Override
        public boolean onContextItemSelected(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
            
		      case R.id.deleteContact: {
		          if(numberOfItemSelected > 0){
		              showConfirmDialog(getResources().getString(R.string.dialog_canhbao),getResources().getString(R.string.dialog_message_xoa), new OnClickListener() {
		                  public void onClick(DialogInterface dialog, int which) {
		                	  
//		                      if (contact.delContactByID(imContactList.get(item_position_long_clicked).getId()) == 0) {
//		                          if (contact.delContactByName(imContactList.get(item_position_long_clicked).getDisplayName()) == 0) {
//		//                            showToast("Sorry");
//		                          } else {
//		                          imContactList.remove(item_position_long_clicked);
//		                          numberOfItemSelected--;
//		                          arrayAdapter.notifyDataSetChanged();
//		                          }
//		                      } else {
//		                          imContactList.remove(item_position_long_clicked);
//		                          numberOfItemSelected--;
//		                          arrayAdapter.notifyDataSetChanged();
//		                      }
		                      
		                  }
		              });
		          }else{
		          	showToast("Chọn danh bạ cần xóa!"); 
		          }
		          break;
		      }
		      case R.id.editContact: {
		          Intent i = new Intent();
		          i.setAction(Intent.ACTION_EDIT);
		          i.setData(Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, "" + imContactList.get(item_position_long_clicked).getId()));
		          startActivity(i);
		          break;
		      }
            }
            return true;
        }
        //tao menu option dua vao file contact_option_menu.xml
        public boolean onCreateOptionsMenu(Menu menu) {
                new MenuInflater(getApplication()).inflate(R.menu.backup_contact_option_menu, menu);                   
                return super.onCreateOptionsMenu(menu);
        }       
        //bat su kien nhan menu item chon tat ca hoac ba chon tat ca cua option menu
        @Override
        public boolean onMenuOpened(int featureId, Menu menu) {
        	if(imContactList.size()!=0){
        		menu.findItem(R.id.sellectAll).setEnabled(true);
                if (numberOfItemSelected == imContactList.size()) {
                    menu.findItem(R.id.sellectAll).setTitle(getResources().getString(R.string.txt_uncheckall));
                } else {
                    menu.findItem(R.id.sellectAll).setTitle(getResources().getString(R.string.txt_checkall));
                }        		
        	}else{
        		menu.findItem(R.id.sellectAll).setEnabled(false);
        	}

        	return super.onMenuOpened(featureId, menu);
        }     
        
        public boolean onOptionsItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                // Options menu
                case R.id.newContact: {
                    Log.i("items size", "" + imContactList.size());
                    Intent i = new Intent();
                    i.setAction(Intent.ACTION_INSERT);
                    i.setData(ContactsContract.Contacts.CONTENT_URI);
                    startActivity(i);
                    break;
                }
                case R.id.exportSDCard:{                   	
                	countItemChecked();
                    if (imContactList.isEmpty()) {
                        showToast("Danh bạ trống!"); 
                    }else {
                        if (numberOfItemSelected == 0) {
                        	showToast("Vui lòng chọn danh bạ để sao lưu!");
                        }else {                        	
                            final ArrayList<MyContact> mycontact = new ArrayList();
                        	final File root = Environment.getExternalStorageDirectory();
                        	final String defaultName = "contact_backup("+MyActivity.getDateTime()+")";
                            edt_name.setText(defaultName);                             
                            showNameFileDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_tentaptin), defaultName, new OnClickListener() {        	    						
								@Override
								public void onClick(DialogInterface dialog, int which){	
									String fileName = edt_name.getText().toString().trim()+".cbk";
									if(checkName(fileName)){
    									File temp = new File(root.getAbsolutePath()+"/BackupManager/Contact");
    			    					temp.mkdirs();
                                        if (temp.canWrite()) {
                                        	final File fileBackup = new File(temp, fileName);
                                            if (fileBackup.exists()){
                                                showConfirmDialog(getResources().getString(R.string.dialog_canhbao), getResources().getString(R.string.dialog_message_ghide), new OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        backupContactToSDCard(mycontact, fileBackup);
                                                    }
                                                });
                                            } else {
                                            	new AsyncTask<Void, Void, Void>(){
                                            		@Override
                                            		protected void onPreExecute() {
                                            			// TODO Auto-generated method stub
                                            			super.onPreExecute();
                                            			progessDialog.setMessage("Đang sao lưu danh bạ ra thẻ nhớ");
                                            			progessDialog.show();
                                            		}
                                            		@Override
                                            		protected Void doInBackground(Void... params) 
                                            		{
                                                        for(imContact icontact:imContactList){                                                        	
                                                            if(icontact.isChecked()){
                                                            	MyContact m =(imContact)icontact;
                                                            	System.out.println(icontact.getDisplayName());
                        										System.out.println(icontact.getId());                            
//                                                            	mycontact.add(contact.getMyContact(icontact.getId()));
                                                            	mycontact.add(m);
                                                            }
                                                        }        		                                            			
                                            	        backupContactToSDCard(mycontact, fileBackup);  
                                            			// TODO Auto-generated method stub
                                            			return null;
                                            		}
                                            		@Override
                                            		protected void onPostExecute(Void result)
                                            		{
                                            			// TODO Auto-generated method stub
                                            			super.onPostExecute(result);
                                            			progessDialog.dismiss();
                                            		       new AlertDialog.Builder(ContactBackupActivity.this).setMessage("Danh bạ "+fileBackup.getName()+"\n đã được sao lưu thành công! ").setTitle(getResources().getString(R.string.dialog_thongbao)).setPositiveButton("Kết Thúc", new OnClickListener() {
											                    public void onClick(DialogInterface dialog, int which) {

											                    }                   
										                    }).show();
									                    	//duyet lai mảng
									                    	for(int i = 0;i < imContactList.size();i++){
									                    		imContactList.get(i).setChecked(false);
									                    	}
									                    	numberOfItemSelected = 0;
									                    	arrayAdapter.notifyDataSetChanged();
                                            		}
                                            	
                                            	}.execute();
                                            }
                                        } else {
                                            showToast("Không thể sao lưu danh bạ lên thẻ nhớ!");
                                        }                                        
            		                    countItemChecked();
            		                 
									}else
										showToast("Tên tập tin không hợp lệ");									        		    									
								}                                  
        		           });                		                               
        		       }                       
        		    };                                               
        		break;
                }        
                
                
                case R.id.sellectAll: {
                	if(imContactList.size() !=0){
                        if (numberOfItemSelected == imContactList.size()) {
                            // Bo chon het danh ba
                            for (MyContact mycontact : imContactList) {
                            	mycontact.setChecked(false);
                            }
                            numberOfItemSelected = 0;                                       
                        } else {
                            // Chon het danh ba
                            for (MyContact contact : imContactList) {
                            	contact.setChecked(true);
                            }
                            numberOfItemSelected = imContactList.size();
                        }
                	}

                    arrayAdapter.notifyDataSetChanged();
                    break;
                }
                
                case R.id.backupToServer: {     
                	countItemChecked();
                    if (imContactList.isEmpty()) {
                            showToast("Danh bạ trống!"); 
                    } else {
                        if (numberOfItemSelected == 0) {
                            showToast("Vui lòng chọn danh bạ để sao lưu!");
                        } else {
                        	//lay thong tin cua danh ba dua vao arraylist
                        	final ArrayList<MyContact> mycontact = new ArrayList();
                        	final File root = Environment.getExternalStorageDirectory();
                        	String defaultName = "contact_backup("+MyActivity.getDateTime()+")";
                            edt_name.setText(defaultName); 
                           
							File temp = new File(root.getAbsolutePath()+"/BackupManager/Contact");
	    					temp.mkdirs(); 
                            if (temp.canWrite()) 
                            {
                            	final File fileBackup = new File(temp, defaultName.trim()+".cbk");
                            	showConfirmDialog("Thông báo","Sao lưu danh bạ lên máy chủ?", new OnClickListener() {									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
										CheckInternet chkI= new CheckInternet(context);
										 if(chkI.checkStatus().equals(true))
											{
											 //bat dau asyncTask 
											 new AsyncTask<Void, Void, Void>()
											 {
												 @Override
													protected void onPreExecute() {
														// TODO Auto-generated method stub
														super.onPreExecute();
														progessDialog.setMessage("Đang sao lưu danh bạ lên máy chủ");
														progessDialog.show();
													}			
												 @Override
												protected Void doInBackground(Void... params) {
													// TODO Auto-generated method stub
													 for(imContact icontact:imContactList){
														 MyContact m = new MyContact();
														 if(icontact.isChecked())
															 m = (imContact)icontact;
//															 mycontact.add(contact.getMyContact(icontact.getId()));	
															 mycontact.add(m);	
							                        	}													 
													backupContactToServer(mycontact, fileBackup);
													return null;
												}
												 @Override
													protected void onPostExecute(Void result) {
														// TODO Auto-generated method stub
													 progessDialog.dismiss();
													        new AlertDialog.Builder(ContactBackupActivity.this).setMessage("Danh bạ "+fileBackup.getName()+"\n đã được sao lưu trên Máy Chủ! ").setTitle(getResources().getString(R.string.dialog_thongbao)).setPositiveButton("Kết Thúc", new OnClickListener() {
											                    public void onClick(DialogInterface dialog, int which) {

											                    }                   
										                    }).show();
													        for (MyContact contact : imContactList) {
								                                contact.setChecked(false);
								                            }
													        numberOfItemSelected = 0;
								                            arrayAdapter.notifyDataSetChanged();
														super.onPostExecute(result);
													}
											 }.execute();
											//ket thuc asyncTask 
											}
										 else{
											 Log.d("ketnoi", "ko co ket noi internet");
											 showToast("Khong co ket noi internet");
										 }
									}
								});
          
                            } else {
                                showToast("Không thể sao lưu danh bạ lên máy chủ!");
                            }                            
                            //thay doi trang thai check cua checkbox
                          
                        }
                    }
                  
                    break;
                }
                
                case R.id.logOut: {
                	logOut();
                    Intent intent = new Intent(ContactBackupActivity.this, LoginActivity.class);
                    startActivity(intent);
                    this.finish();
                    break;
                }
                
                case R.id.deleteContact:{
                	
                	if(numberOfItemSelected > 0){
                		showConfirmDialog(getResources().getString(R.string.dialog_thongbao), "Bạn có muốn xóa danh bạ?", new OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								 //bat dau asyncTask 
								 new AsyncTask<Void, Void, Void>()
								 {
									 @Override
										protected void onPreExecute() {
											// TODO Auto-generated method stub
											super.onPreExecute();
											progessDialog.setMessage("Đang xóa danh bạ");
											progessDialog.show();
										}			
									 @Override
									protected Void doInBackground(Void... params) {
										// TODO Auto-generated method stub						
										 deleteContact();
										 progessDialog.dismiss();
										 
//					                      if (contact.delContactByID(imContactList.get(item_position_long_clicked).getId()) == 0) {
//				                          if (contact.delContactByName(imContactList.get(item_position_long_clicked).getDisplayName()) == 0) {
//				//                            showToast("Sorry");
//				                          } else {
//				                          imContactList.remove(item_position_long_clicked);
//				                          numberOfItemSelected--;
//				                          arrayAdapter.notifyDataSetChanged();
//				                          }
//				                      } else {
//				                          imContactList.remove(item_position_long_clicked);
//				                          numberOfItemSelected--;
//				                          arrayAdapter.notifyDataSetChanged();
//				                      }										 
										 numberOfItemSelected = 0;
										return null;
									}
									 @Override
										protected void onPostExecute(Void result) {
											// TODO Auto-generated method stub
											arrayAdapter.notifyDataSetChanged();
											progessDialog.dismiss();
											super.onPostExecute(result);
										}
								 }.execute();
								//ket thuc asyncTask 
							}
                		});		
                		
                		arrayAdapter.notifyDataSetChanged();
                	}else{
                		showToast("Vui lòng chọn danh bạ cần xóa");
                	}
                	arrayAdapter.notifyDataSetChanged();
                	
                	break;
                }
            }
            return super.onOptionsItemSelected(item);
        }       
        
        private void deleteContact(){
        	try{
    			for(int i=0 ;i < imContactList.size();i++){
    				MyContact mcontact = imContactList.get(i);    				
    				if(mcontact.isChecked()){
    					System.out.println("numberOfItemSelected(del): "+numberOfItemSelected);
    					System.out.println("id deleted: "+mcontact.getId().toString());
    					if (contact.delContactByID(mcontact.getId()) == 0) {
	                          if (contact.delContactByName(mcontact.getDisplayName()) == 0) {
	//                            showToast("Sorry");
	                          } else {
	          					imContactList.remove(mcontact);
	          					numberOfItemSelected--;
	          					i--;
	                          }
	                      } else {
	          					imContactList.remove(mcontact);
	          					numberOfItemSelected--;
	          					i--;
	                      }	    					    					
    				}
    			}
        	}catch(Exception ex){
        		System.out.println("loi xoa danh ba: "+ex.toString().trim());
        	}

        }
        
        private void backupContactToSDCard(ArrayList<MyContact> contactBackup, final File exportFile) {
            try {
            	if (contactBackup.isEmpty()) {
					System.out.println("List rong");
				}
            	else{
            		for (int i =0 ;i<contactBackup.size();i++)
                    	{
                    		System.out.println(i);
        
       
                    	}	
            	}
//            	
                FileOutputStream fout= new FileOutputStream(exportFile);
                OutputStreamWriter osw = new OutputStreamWriter(fout);                  
                String xml = xStreamXML.contactToXML(contactBackup);
                System.out.print(xml);
                osw.write(xml);
                osw.flush();
                osw.close();
                System.out.println("String getAbsolutePath(): "+exportFile.getAbsolutePath());
                System.out.println("long getTotalSpace(): "+exportFile.getTotalSpace());
                System.out.println("String getPath(): "+exportFile.getPath());
                System.out.println("long getFreeSpace(): "+exportFile.getFreeSpace());
            } catch (IOException e) {
              System.out.println("loi khi sao luu danh ba tren the nho!");
            }           
        }       
        
        public void backupContactToServer(ArrayList<MyContact> contactBackup, File contactFile)
        {
            try {
            		//thuc hien ghi du lieu len file
                	String fileName = contactFile.getName();
                    FileOutputStream fout= new FileOutputStream(contactFile);
                    OutputStreamWriter osw = new OutputStreamWriter(fout);                  
                    String xml = xStreamXML.contactToXML(contactBackup);//parse list contact thanh dang xml co cau truc
                    osw.write(xml);
                    osw.flush();
                    osw.close();
                    // thuc thi ma hoa tập tin
                	Log.v("tag",contactFile.getPath());
                	aes= new AESControl(username);
                	String output= contactFile.getPath()+".aes";
                	aes.EncFile(contactFile.getPath(), output);
                	FileInputStream fis= new FileInputStream(output);
    				
    				Log.v("tag",output);
                    String temp = String.valueOf(userid)+"@"+String.valueOf(contactFileType)+"@"+"sao luu tap tin danh ba!";
                    Log.d("chuoi ket noi ",urlString);
                    httpUploader htfu = new httpUploader(urlString,temp, fileName);
                    contactFile.delete();
                    File encryptFile= new File(output);
                    encryptFile.delete();
                    System.out.println("chuoi tra ve la: "+htfu.doStart(fis));
                        //lay cac thong tin cua file gui len server de ghi len database
                        //bat dau upload file len server
                        //hoan tat upload file va ghi thong tin file len server
                        //xoa file tam da tao tren sdcard
            
            } catch (IOException e) {
              System.out.println("loi khi sao luu danh ba len may chu !");
            }                
        }
        
    	private boolean checkName(String name) {
    		return name.matches("([a-zA-Z0-9_\\-\\.()]+)");
    	}
	    @Override
	    public boolean onKeyDown(int keyCode, KeyEvent event) {
	    	// TODO Auto-generated method stub
	    	if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0)
	    	{
	    		
						finish();
					
	    	}
	    	return super.onKeyDown(keyCode, event);
	    }
        
        //moi autogeneral
            	    
	    public AlertDialog showNameFileDialog(String title, String msg, String defaultName, OnClickListener yesClick)
	    {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIcon(R.drawable.ic_error);
			edt_name = new EditText(this);			
//		    edt_name.setSingleLine();
		    edt_name.setText(defaultName);
		    builder.setView(edt_name);
			if(title!=null) builder.setTitle(title);
			if(msg!=null) builder.setMessage(msg);
			return builder.setPositiveButton(getResources().getString(R.string.txt_Yes), yesClick).setNegativeButton(getResources().getString(R.string.txt_No), new OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).show();
		}
	
    	public ProgressDialog showProgress(String title, String msg, int icon, boolean cancelable) {
    		ProgressDialog pdialog = new ProgressDialog(this);
    		if (title != null) {
    			pdialog.setTitle(title);
    		}
    		if (msg != null)
    			pdialog.setMessage(msg);
    		if (icon != -1) {
    			pdialog.setIcon(icon);
    		}
    		pdialog.setCancelable(cancelable);
    		pdialog.show();
    		return pdialog;
    	}

}
